# Prepare NV returns
# Note: clean and rearrange 2020 NV returns
# By Dom Valentino and Chris Kenny
# libs --------------------------------------------------------------------
library(tidyverse) # select(), filter(), mutate(), etc.
library(haven) # read_dta()

# data --------------------------------------------------------------------
nv2020 <- read.csv(file = '../data/returns_nv/returns_nv_original.csv', header = F)
cvap <- read_dta("../data/modified data/county_cvap.dta")
turnout <- read.csv("../data/returns_nv/turnout_nv_original.csv")

# clean
final_nv <- nv2020 %>% filter(!(V1 %in% c("Percent", "Total Votes"))) %>% 
  transmute(county = V1, 
            fips = case_when( # hard code county fips
              county == "Carson City" ~ "32510",
              county == "Churchill" ~ "32001",
              county == "Clark" ~ "32003",
              county == "Douglas" ~ "32005",
              county == "Elko" ~ "32007",
              county == "Esmeralda" ~ "32009",
              county == "Eureka" ~ "32011",
              county == "Humboldt" ~ "32013",
              county == "Lander" ~ "32015",
              county == "Lincoln" ~ "32017",
              county == "Lyon" ~ "32019",
              county == "Mineral" ~ "32021",
              county == "Nye" ~ "32023",
              county == "Pershing" ~ "32027",
              county == "Storey" ~ "32029",
              county == "Washoe" ~ "32031",
              county == "White Pine" ~ "32033"
            ),
            treat = 1,
            dem_share_pres = V2 / (V2 + V3), 
            dem_share_sen = NA_real_,
            dem_share_gov = NA_real_,
            year = 2020) %>% 
  left_join(., turnout, by = "county") %>% # merge turnout
  left_join(., cvap[cvap$year == 2020 & cvap$state == "NV", ], by = "county") %>% 
  mutate(year = year.x, turnout_share = ballots_cast / cvap_approx) %>% 
  select(-year.y, -year.x)

write_csv(final_nv, "../data/analysis/analysis_nv.csv")
